//Copyright (c) 2010, Goodwine & Tibia ML
//Licensed under new BSD License.

// Function added to onclick event in the link.
removeCharacter = function ()
{
	var character = this.parentElement.previousSibling.previousSibling.innerText.match(/^ (.*?)$/i)[1];
	var temp = localStorage.characters.split(' | ');
	var newTemp = [];
	var x;
	while(x = temp.pop())
	{
		var values = x.split(' , ');
		if(values[0]!=character)
			newTemp.push(x);
	}
	newTemp.reverse();
	localStorage.characters = newTemp.join(' | ');
	showCharacterList();
	_trackOption('Notify Character', 'remove');
};

// Function shows the character list of the notification list.
function showCharacterList(autoupdate)
{
	// If it was auto updated?
	var autoupdate = autoupdate || false;
	var div = document.getElementById('charList');
	// Creating the list.
	div.innerHTML="";
	// Load the characters.
	localStorage.characters = localStorage.characters || "";
	// Parse the characters.
	var temp = localStorage.characters.split(' | ');
	// Amounts of characters ( Used for Statistics )
	var amount = 0;
	for(var i in temp)
	{
		var values = temp[i].split(' , ');
		if(values[0].length > 0)
		{
			amount ++;
			var name = document.createElement('div'), world = document.createElement('div'), row = document.createElement('div');
			var ops = document.createElement('div');
			var remove = document.createElement('a');
			remove.innerText="[Remove]";
			remove.href="javascript:;";
			remove.onclick = removeCharacter;
			ops.appendChild(remove);
			ops.className="ops";
			// Add icons to the list.
			var charsIn = localStorage.charsOnline;
			var show = false;
			if(charsIn && charsIn.length > 0) {
				charsIn = charsIn.split(' | ');
				for(var j in charsIn)
					if(charsIn[j] == values[0]) {
						show = true;
						break;
					}
			}
			if(show)
				name.innerHTML = '<img height="16px" src="' + chrome.extension.getURL('images/green icon.svg') + '" /><span class="top"> ' + values[0] + '</span>';
			else
				name.innerHTML = '<img height="16px" src="' + chrome.extension.getURL('images/gray icon.svg') + '" /><span class="top"> ' + values[0] + '</span>';
			world.innerText=values[1];
			name.className="name";
			world.className="world";
			row.className="row";
			row.appendChild(name);
			row.appendChild(world);
			row.appendChild(ops);
			div.appendChild(row);
		}
	}
	_trackOption('Notify Total Characters', amount);
	// Recalls if characters should be nottified on start.
	recallCharNotOnStart();
	if(!autoupdate)
		enableCharacterControls(false);
}
// Recalls if characters should be nottified on start.
function recallCharNotOnStart()
{
	if(!localStorage.charNotOnStart)
		localStorage.charNotOnStart = true;
	charNotOnStart.checked = JSON.parse(localStorage.charNotOnStart);
	charNotifications.character.value = "";
}

// Saves a new character.
function saveCharacterInfo(character)
{
	// Validates null input.
	if(character.length < 1)
	{
		alert("Insert the character's name!");
		return;
	}
	localStorage.characters = localStorage.characters || "";
	// Checks if character was already added.
	var temp = localStorage.characters.split(' | ');
	// Remove parse error.
	if(!temp[0] || temp[0].search(' , ') < 0)
	{
		temp.reverse();
		temp.pop();
		temp.reverse();
	}
	for(var i in temp)
	{
		var values = temp[i].split(' , ');
		for(var j in values)
			if(character.toLowerCase() == values[j].toLowerCase())
			{
				alert("Character is already added!");
				return;
			}
	}
	// If the characters are less than or equal to 5. XHR to see if character exists.
	if(temp.length < 5)
	{
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function() 
		{
			// Loading screen.
			if (xhr.readyState == 1)
			{
				bg = document.createElement('div');
				var sq = document.createElement('div');
				bg.appendChild(sq);
				bg.style.zIndex = "9359";
				bg.style.height = "100%";
				bg.style.width = "100%";
				bg.style.position = "fixed";
				bg.style.top = "0";
				bg.style.left = "0";
				bg.style.opacity = "0.5";
				bg.style.background = "#000000";
				sq.style.marginTop = "-50px";
				sq.style.marginLeft = "-50px";
				sq.style.height = "100px";
				sq.style.width = "100px";
				sq.style.borderRadius = "30px";
				sq.style.position = "fixed";
				sq.style.top = "50%";
				sq.style.left = "50%";
				sq.style.background = "#FFFFFF url(options/loader.gif) no-repeat center";
				document.getElementsByTagName('body')[0].appendChild(bg);
			}
			if (xhr.readyState == 4)
			{
				bg.parentElement.removeChild(bg);
				if (xhr.status == 200)
				{
					var data = xhr.responseText;
					if(data.match(/<TD>Character <B>.*?<\/B> does not exist\.<\/TD>/ig))
						alert('Character Doesn\'t Exist');
					else
					{
						var world = data.match(/<TD>World:<\/TD><TD>(.*?)<\/TD>/i);
						var character = data.match(/<TD WIDTH=20%>Name:<\/TD><TD>(.*?) ?<div.*?>/i);
						var temp = localStorage.characters.split(' | ');
						if(!character)
						{
							alert('Character Doesn\'t Exist');
							return;
						}
						// Verify if the character was already added, again.
						for(var i in temp)
						{
							var values = temp[i].split(' , ');
							for(var j in values)
								if(character[1].toLowerCase() == values[j].toLowerCase())
								{
									alert("Character is already added!");
									return;
								}
						}
						_trackOption('Notify Character', 'add');
						// Add the character to the list and update.
						temp.push(character[1] + ' , ' + world[1]);
						localStorage.characters = temp.join(' | ').replace(/^  \| /,'');
						showCharacterList();
						enableCharacterControls(false);
					}
				}
				// If it couldn't save the character or determine if it was valid or the XHR failed, then return FAIL.
				else
					alert('There was an error with the query, please try again.\nIf problems persists, check your connection.');
			}
		}
		var url = 'http://www.tibia.com/community/?subtopic=characters&name='+character;
		xhr.open('GET', url, true);
		xhr.send();
	}
	else
		alert('You can only be notified of maximum 5 characters.');
}

$(function() {
	$('#charNotifications input[type*=text]').change(enableCharacterControls).keydown(enableCharacterControls);
	showCharacterList();
});

function enableCharacterControls(enabled) {
	enabled = enabled || false;
	$('#charNotifications input[type*=submit]').attr('disabled', !enabled);
}

// When the caracter gets a notification, update the list.
chrome.extension.onRequest.addListener(function(request, sender, callback) {
	if(request.updateCharList != null)
		showCharacterList(true);
});